package com.uvstu.common.utils.sign;

import javax.crypto.Cipher;
import java.security.KeyFactory;
import java.security.PublicKey;
import java.security.spec.X509EncodedKeySpec;
import org.apache.commons.codec.binary.Base64;

public class RSAUtils {

    private static final String publicKeyText = "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQC7vqtzOPC+ObdSCKhuonCkD4jfSz7lVO1MSwsENte7EsCmDgTgL/5m8dT6YHbXeo9Ad8+73uj0cwlHJR9b4M6/zE4fOAc3NukHXcQKiODdHe4ABmUdG+9n0dCaF8RhJl8OVE8muyuye2PdfvTMfGA6ZeneCTksUbF6Jab9Mx5CDQIDAQAB";

    /**
     * 公钥加密方法
     *
     * @param text          将要加密的信息
     * @return Base64编码的字符串
     * @throws Exception
     */
    public static String encryptByPublicKey(String text) {
        try {
            // 返回按照 X.509 标准进行编码的密钥的字节
            // x509EncodedKeySpec2 是一种规范、规格
            X509EncodedKeySpec x509EncodedKeySpec2 = new X509EncodedKeySpec(Base64.decodeBase64(publicKeyText));
            KeyFactory keyFactory = KeyFactory.getInstance("RSA");
            // 让密钥工厂按照指定的 规范 生成公钥
            PublicKey publicKey = keyFactory.generatePublic(x509EncodedKeySpec2);
            Cipher cipher = Cipher.getInstance("RSA");
            // 对加密初始化，使用加密模式，公钥加密
            // Cipher.ENCRYPT_MODE 可以用 1 代替
            cipher.init(Cipher.ENCRYPT_MODE, publicKey);

            byte[] result = cipher.doFinal(text.getBytes());
            // 返回 Base64编码的字符串
            return Base64.encodeBase64String(result);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 公钥解密方法
     *
     * @param text          待解密的信息
     * @return 字符串
     * @throws Exception
     */
    public static String decryptByPublicKey(String text) {
        try {
            X509EncodedKeySpec x509EncodedKeySpec = new X509EncodedKeySpec(Base64.decodeBase64(publicKeyText));
            KeyFactory keyFactory = KeyFactory.getInstance("RSA");
            PublicKey publicKey = keyFactory.generatePublic(x509EncodedKeySpec);
            Cipher cipher = Cipher.getInstance("RSA");
            cipher.init(Cipher.DECRYPT_MODE, publicKey);
            byte[] result = cipher.doFinal(Base64.decodeBase64(text));
            return new String(result);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

}
